package org.xxl.iso 
{
	import flash.display.Sprite;
	import flash.geom.Point;
	
	/**
	 * ...
	 * @author XXL
	 */
	public class IsoWorld extends Sprite 
	{
		private var _showGrid:Boolean = false;
		private var _width:int;
		private var _height:int;
		private var _size:int;
		
		protected var _objects:Array;
		protected var _needSort:Boolean = true;
		
		private var _grid:Sprite;
		private var _world:Sprite;
		
		public function IsoWorld(width:int, height:int, size:int ) 
		{
			this._width = width;
			this._height = height;
			this._size = size;
			
			_objects = [];
			_world = new Sprite();
			addChild(_world);
		}
		
		public function reInit(width:int, height:int, size:int):void
		{
			this._width = width;
			this._height = height;
			this._size = size;
			if (_grid)
			{
				removeChild(_grid);
				_grid = null;
			}
		}
		
		public function parseLogicPos(pos:Point3D):Point3D
		{
			var newPos:Point3D = new Point3D();
			newPos.x = Math.round(pos.x / _size);
			newPos.y = Math.round(pos.y / _size);
			newPos.z = Math.round(pos.z / _size);
			return newPos;
		}
		
		public function clear():void
		{
			while (_world.numChildren > 0)
			{
				_world.removeChildAt(0);
			}
			_objects = [];
			_needSort = false;
		}
		
		public function addChildToWorld(child:IsoObject):void
		{
			_world.addChild(child);
			_objects.push(child);
			_needSort = true;
		}
		
		public function removeChildFromWorld(child:IsoObject):void
		{
			var index:int = _objects.indexOf(child);
			if (index >= 0)
			{
				_objects.splice(index, 1);
				_world.removeChild(child);
				_needSort = true;
			}
		}
		
		public function sort():void
		{
			_objects.sortOn("depth", Array.NUMERIC);
			var len:int = _objects.length;
			for (var i:int = 0; i < len; i++) 
			{
				_world.setChildIndex(_objects[i], i);
			}
		}
		
		public function render():void
		{
			if (_showGrid)
			{
				drawGrid();
			}
			if (_needSort)
			{
				_needSort = false;
				sort();
			}
			for each(var child:IsoObject in _objects)
			{
				child.render();
			}
		}
		
		public function set showGrid(value:Boolean):void
		{
			_showGrid = value;
			if (_showGrid == false)
			{
				_grid.visible = false;
			}
		}
		public function get showGrid():Boolean
		{
			return _showGrid;
		}
		
		private function drawGrid():void 
		{
			if (_grid == null)
			{
				_grid = new Sprite();
				_grid.mouseEnabled = false;
				_grid.mouseChildren = false;
				for (var i:int = 0; i < _width; i++) 
				{
					for (var j:int = 0; j < _height; j++) 
					{
						var tile:DrawnIsoTile = new DrawnIsoTile(_size);
						tile.position = new Point3D(i * _size, 0, j * _size);
						_grid.addChild(tile);
					}
				}
				addChild(_grid);
				addChild(_world);
			}
			_grid.visible = true;
		}
	}

}